/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2007 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: header,v 1.16.2.1.2.1 2007/01/01 19:32:09 iliaa Exp $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "main/SAPI.h"
#include "ext/standard/info.h"
#include "ext/standard/php_string.h"
#include "ext/standard/php_smart_str.h"  
#include "ext/standard/php_filestat.h"

#include "php_waf_framework.h"
#include "waf_controller.h"
#include "waf_view.h"

zval * request_var(uint type, char * name, uint len TSRMLS_DC) {
	zval **carrier = NULL, **ret;

	switch (type) {
		case POST:
		case GET:
		case FILES:
		case COOKIE:
		case ENV:
		case SERVER:
			carrier = &PG(http_globals)[type];
			break;
		case REQUEST:
			(void)zend_hash_find(&EG(symbol_table), ZEND_STRS("_REQUEST"), (void **)&carrier);
			break;
		default:
			break;
	}

	if(!carrier || !(*carrier) || !len) 
    {
        return NULL;
	}

	if(zend_hash_find(Z_ARRVAL_PP(carrier), name, len + 1, (void **)&ret) == FAILURE) 
    {
        return NULL;
	}

	return *ret;
}

/*
char * get_file_path(zval *config, char * cpkey)
{
   smart_str filepath = {0};


    
}
*/

void cli_param_parse_to_get(zval **cmds)
{
    zval *d1, *d2, *params_meta, **carrier;

    MAKE_STD_ZVAL(d1);
    ZVAL_STRINGL(d1, "&", 1, 1);

    MAKE_STD_ZVAL(d2);
    ZVAL_STRINGL(d2, "=", 1, 1);

    MAKE_STD_ZVAL(params_meta);
    array_init(params_meta);

    php_explode(d1, *cmds, params_meta, 30);

    // get $_GET
    if(zend_hash_find(&EG(symbol_table), ZEND_STRS("_GET"), (void **)&carrier) != SUCCESS)
    {
        return;
    }

    zval **operand;
    for(    zend_hash_internal_pointer_reset(Z_ARRVAL_P(params_meta));
            zend_hash_get_current_data(Z_ARRVAL_P(params_meta), (void **)&operand) == SUCCESS;
            zend_hash_move_forward(Z_ARRVAL_P(params_meta)))
    {
        zval *param, **k = NULL, **v = NULL;
        MAKE_STD_ZVAL(param);
        array_init(param);

        php_explode(d2, *operand, param, 2);

        if(zend_hash_index_find(Z_ARRVAL_P(param), 0, (void**)&k) == SUCCESS &&
            zend_hash_index_find(Z_ARRVAL_P(param), 1, (void**)&v) == SUCCESS)
        {
            add_assoc_stringl(*carrier, Z_STRVAL_PP(k), Z_STRVAL_PP(v), Z_STRLEN_PP(v), 1);
        }
        
        zval_ptr_dtor(&param);
    }

    zval_ptr_dtor(&d1);
    zval_ptr_dtor(&d2);
    zval_ptr_dtor(&params_meta);
}
/*
zval * get_item_by_ht(HashTable *ht, char *htKey)
{
    zval **retVal, *retValue;
    php_printf("1, htKey=%s :\n", htKey);
    char *strTest = "c";
    if( zend_hash_find(ht, ZEND_STRS(strTest), (void **)&retVal) != SUCCESS)
    {
        return NULL;
    }
    VAR_DUMP_PP(retVal);
php_printf("2:\n");
    MAKE_STD_ZVAL(retValue);
    retValue = *retVal;
    zval_copy_ctor(retValue);

    return retValue;
}
*/

int include(char *path){
	zend_op_array *op_array;
	zend_file_handle file_handle;

	if(zend_stream_open(path, &file_handle TSRMLS_CC) == SUCCESS){
		zval **fooval;
		op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC);

		//ALLOC_HASHTABLE(EG(active_symbol_table));
		//zend_hash_init(EG(active_symbol_table), 0, NULL, ZVAL_PTR_DTOR, 0);

		if (op_array && file_handle.handle.stream.handle) {
			int dummy = 1;
			zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL);
		}
		zend_destroy_file_handle(&file_handle TSRMLS_CC);

		if (op_array) {
			zval *result					= NULL;
			STORE_EG_ENVIRON();

			EG(return_value_ptr_ptr)	= &result;
			EG(active_op_array) 		= op_array;

	#if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 2)) || (PHP_MAJOR_VERSION > 5)
			if (!EG(active_symbol_table)) {
				zend_rebuild_symbol_table(TSRMLS_C);
			}
	#endif
			zend_execute(op_array TSRMLS_CC);

			destroy_op_array(op_array TSRMLS_CC);
			efree(op_array);

			if (!EG(exception)) {
				if (EG(return_value_ptr_ptr)) {
					zval_ptr_dtor(EG(return_value_ptr_ptr));
				}
			}

			RESTORE_EG_ENVIRON();
		}

	}else{
		zend_error(E_ERROR, "%s does not open", path);
		return 1;
	}
}

/* If you declare any globals in php_waf_framework.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(waf_framework)
*/

/* True global resources - no need for thread safety here */
static int le_waf_framework;
zend_class_entry * waf_framework_ce;

/* {{{ waf_framework_functions[]
 *
 * Every user visible function must have an entry in waf_framework_functions[].
 */
zend_function_entry waf_framework_functions[] = {
	PHP_FE(confirm_waf_framework_compiled,	NULL)		/* For testing, remove later. */
	{NULL, NULL, NULL}	/* Must be the last line in waf_framework_functions[] */
};
/* }}} */

/* {{{ waf_framework_module_entry
 */
zend_module_entry waf_framework_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
	STANDARD_MODULE_HEADER,
#endif
	"waf_framework",
	waf_framework_functions,
	PHP_MINIT(waf_framework),
	PHP_MSHUTDOWN(waf_framework),
	PHP_RINIT(waf_framework),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(waf_framework),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(waf_framework),
#if ZEND_MODULE_API_NO >= 20010901
	"0.1", /* Replace with version number for your extension */
#endif
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_WAF_FRAMEWORK
ZEND_GET_MODULE(waf_framework)
#endif

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("waf_framework.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_waf_framework_globals, waf_framework_globals)
    STD_PHP_INI_ENTRY("waf_framework.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_waf_framework_globals, waf_framework_globals)
PHP_INI_END()
*/
/* }}} */

/* {{{ php_waf_framework_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_waf_framework_init_globals(zend_waf_framework_globals *waf_framework_globals)
{
	waf_framework_globals->global_value = 0;
	waf_framework_globals->global_string = NULL;
}
*/
/* }}} */

PHP_METHOD(waf_framework, __construct)
{
}

PHP_METHOD(waf_framework, __destruct)
{
}

PHP_METHOD(waf_framework, getInstance)
{
        zval * instance;
        instance = zend_read_static_property(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_INSTANCE), 1 TSRMLS_CC);
        if(ZVAL_IS_NULL(instance))
        {
         	// update static propetry instance
		    MAKE_STD_ZVAL(instance);
            object_init_ex(instance, waf_framework_ce);
		    zend_update_static_property(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_INSTANCE), instance TSRMLS_CC); 

                RETVAL_ZVAL(instance, 1, 1);
        }else{
                RETVAL_ZVAL(instance, 1, 0);
	}
}

PHP_METHOD(waf_framework, run)
{
	// config
	zval *config;
	if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &config) == FAILURE)
	{
		return;
	}else{
        zend_update_static_property(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_CONFIG), config TSRMLS_CC);
	}

    // parse request cli or web
    // cli
    if(strcmp(sapi_module.name, "cli") == 0)
    {
        zval *server;

        //find $_SERVER
        server = PG(http_globals)[SERVER];
        if( !(!server && ZVAL_IS_NULL(server)))
        {
            // find argv
            zval **retVal;
            if(zend_hash_find(Z_ARRVAL_P(server), "argv", sizeof("argv"), (void**)&retVal) == SUCCESS)
            {
                // find param 1
                zval **ret2Val;
                if(zend_hash_index_find(Z_ARRVAL_PP(retVal), 1, (void **)&ret2Val) == SUCCESS)
                {
                    // replace $_GET 
                    cli_param_parse_to_get(ret2Val);
                }
            }
        }
    }
    // web
    else
    {   
        //php_printf("web");
    }

    // param the $_GET, get the controll and model
    zval **retGet;
    if(zend_hash_find(&EG(symbol_table), ZEND_STRS("_GET"), (void **)&retGet) != SUCCESS)
    {
        // todo goto error
    }

	zend_class_entry *controller_ce;
	zval *controller_obj, **controller_name, **controller_action, *controller_name_p, *controller_action_p;

    if(zend_hash_find(Z_ARRVAL_PP(retGet), ZEND_STRS("c"), (void**)&controller_name) != SUCCESS)
    {
        MAKE_STD_ZVAL(controller_name_p);
        ZVAL_STRING(controller_name_p, "site", 1);
    }else{
        controller_name_p = *controller_name;
    }

    if(zend_hash_find(Z_ARRVAL_PP(retGet), ZEND_STRS("a"), (void**)&controller_action) != SUCCESS)
    {
        MAKE_STD_ZVAL(controller_action_p);
        ZVAL_STRING(controller_action_p, "index", 1);
    }else{
        controller_action_p = *controller_action;
    }

    // deal class name and action name
    char * controller_name_pstr     = php_strtolower(Z_STRVAL_P(controller_name_p), Z_STRLEN_P(controller_name_p));
    char * controller_action_pstr   = php_strtolower(Z_STRVAL_P(controller_action_p), Z_STRLEN_P(controller_action_p));
    *controller_name_pstr           = toupper(*controller_name_pstr);
    *controller_action_pstr         = toupper(*controller_action_pstr);

    smart_str ss_controller_name    = {0};
    smart_str ss_controller_action  = {0};

    smart_str_appends(&ss_controller_name,  controller_name_pstr);
    smart_str_appends(&ss_controller_name,  "Controller");
    smart_str_0(&ss_controller_name);

    smart_str_appends(&ss_controller_action,  "action");
    smart_str_appends(&ss_controller_action,  controller_action_pstr);
    smart_str_0(&ss_controller_action);
    
    zval * controller_name_call, *controller_action_call;
    MAKE_STD_ZVAL(controller_name_call);
    ZVAL_STRINGL(controller_name_call, ss_controller_name.c, ss_controller_name.len, 1);

    MAKE_STD_ZVAL(controller_action_call);
    ZVAL_STRINGL(controller_action_call, ss_controller_action.c, ss_controller_action.len, 1);

    // include file
    zval **retAppRoot;
    smart_str controller_path = {0};

    if(zend_hash_find(Z_ARRVAL_P(config), ZEND_STRS("APP_ROOT"), (void**)&retAppRoot) != SUCCESS)
    {
        //return NULL; // todo
    }
    
    smart_str_appends(&controller_path, Z_STRVAL_PP(retAppRoot));
    smart_str_appends(&controller_path, "/controllers/");
    smart_str_appends(&controller_path, ss_controller_name.c);
    smart_str_appends(&controller_path, ".php");
    smart_str_0(&controller_path);

    include(controller_path.c);
    
    smart_str_free(&controller_path);
    smart_str_free(&ss_controller_name);
    smart_str_free(&ss_controller_action);

	controller_ce = get_class_entry(Z_STRVAL_P(controller_name_call), Z_STRLEN_P(controller_name_call));	

	MAKE_STD_ZVAL(controller_obj);
	object_init_ex(controller_obj, controller_ce);

	// do call function
	zval *retVal;
	MAKE_STD_ZVAL(retVal);

    // call controller __construct
    zval * controller_construct;
    MAKE_STD_ZVAL(controller_construct);
    ZVAL_STRING(controller_construct, "__construct", 1);
    call_user_function(&(controller_ce->function_table), &controller_obj, controller_construct, retVal, 0, NULL TSRMLS_CC);
    zval_ptr_dtor(&controller_construct);

    // call action function
	call_user_function(&(controller_ce->function_table), &controller_obj, controller_action_call, retVal, 0, NULL TSRMLS_CC);

	// destory	
	zval_ptr_dtor(&retVal);
	zval_ptr_dtor(&controller_obj);
    zval_ptr_dtor(&controller_name_p);
    zval_ptr_dtor(&controller_action_p);
    zval_ptr_dtor(&controller_name_call);
    zval_ptr_dtor(&controller_action_call);
}

PHP_METHOD(waf_framework, getConfig)
{
    zval *config = zend_read_static_property(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_CONFIG), 1 TSRMLS_CC);
    RETURN_ZVAL(config, 1, 0);
}

PHP_METHOD(waf_framework, route)
{

}

zend_function_entry waf_framework_methods[] = {
        PHP_ME(waf_framework,   __construct,    NULL,   ZEND_ACC_PRIVATE | ZEND_ACC_CTOR)
        PHP_ME(waf_framework,   __destruct,     NULL,   ZEND_ACC_PUBLIC | ZEND_ACC_DTOR)
        PHP_ME(waf_framework,   getInstance,	NULL,   ZEND_ACC_STATIC | ZEND_ACC_PUBLIC)
	    PHP_ME(waf_framework,	run,		    NULL,	ZEND_ACC_PUBLIC)
        PHP_ME(waf_framework,   getConfig,      NULL,   ZEND_ACC_STATIC | ZEND_ACC_PUBLIC)
        PHP_ME(waf_framework,   route,          NULL,   ZEND_ACC_PUBLIC)
        {NULL, NULL, NULL}
};


/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(waf_framework)
{
	/* If you have INI entries, uncomment these lines 
	REGISTER_INI_ENTRIES();
	*/

	zend_class_entry ce;
	INIT_CLASS_ENTRY(ce, "Waf_Framework", waf_framework_methods);
	waf_framework_ce = zend_register_internal_class_ex(&ce, NULL, NULL TSRMLS_CC);

	zend_declare_property_null(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_INSTANCE), ZEND_ACC_STATIC | ZEND_ACC_PROTECTED TSRMLS_CC);
	zend_declare_property_null(waf_framework_ce, ZEND_STRL(WAF_FRAMEWORK_STATIC_PROPERTY_CONFIG), ZEND_ACC_STATIC | ZEND_ACC_PROTECTED TSRMLS_CC);


	WAF_STARTUP(waf_controller);
    WAF_STARTUP(waf_view);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(waf_framework)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(waf_framework)
{
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(waf_framework)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(waf_framework)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "waf_framework support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */


/* Remove the following function when you have succesfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_waf_framework_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_waf_framework_compiled)
{
	char *arg = NULL;
	int arg_len, len;
	char *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "waf_framework", arg);
	RETURN_STRINGL(strg, len, 0);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and 
   unfold functions in source code. See the corresponding marks just before 
   function definition, where the functions purpose is also documented. Please 
   follow this convention for the convenience of others editing your code.
*/

//user define function
zend_class_entry *get_class_entry(char *class_name, int class_name_len TSRMLS_DC){
    zend_class_entry **ce;

    if (zend_lookup_class(class_name, class_name_len, &ce TSRMLS_CC) == SUCCESS) {
        return *ce;
    } else {
        return NULL;
    }   
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
